<template>
  <div id="approve-list" class="manage-pos">
    <tag-box>
      <template v-slot:approve>
        <template v-if="!showChild">
          <div class="opentype-tag"
               :class="{'choose-bg-tag': apiType === 'todo'}"
               @click="toggleStatus('todo')"
          >待办 {{ todoTotal }}</div>
          <div class="opentype-tag opentype-tag-2"
               :class="{'choose-bg-tag': apiType === 'done'}"
               @click="toggleStatus('done')"
          >已办 {{ doneTotal }}</div>
        </template>
        <template v-if="showChild">
          <div v-if="openType === 1" class="opentype-tag choose-bg-tag">请假审批单</div>
          <div v-if="openType === 2" class="opentype-tag choose-bg-tag">流程审批进度历史</div>
          <div v-if="openType === 3" class="opentype-tag choose-bg-tag">请假单详情</div>
        </template>
      </template>
    </tag-box>
    <div style="height: 26px;" v-show="!showChild"></div>
    <div class="dep_top" v-show="!showChild">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="用户名">
                <a-input
                  v-model="queryParam.userName"
                  clearable
                  placeholder="请输入"
                ></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="部门">
                <a-select v-model="queryParam.dept"
                          placeholder="请选择">
                  <a-select-option value="">请选择</a-select-option>
                  <a-select-option v-for="(item) in departments"
                                   :key="item.id"
                                   :value="item.name">
              <span style="display: inline-block;width: 100%"
                    :title=" item.name">
                {{ item.name}}
              </span>
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
          <span class="table-edit-submitButtons">
            <a-button class="ml8" @click="selectApprove(1)">查询</a-button>
            <a-button type="primary" class="ml8" @click="selectApprove(2)">重置</a-button>
          </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </div>
    <div class="dep_main" v-show="!showChild">
      <a-table
        bordered
        ref="table"
        size="middle"
        rowKey="id"
        :columns="columns"
        :data-source="listData"
        :pagination="paginationInfo"
        :loading="loading"
        @change="handleTableChange">
        <span slot="leaveTypeAction" slot-scope="text, record">
          {{ filterDictOptions(text).item_desc }}
        </span>
        <span slot="action" slot-scope="text, record">
          <template v-if="apiType === 'todo'">
             <a
               @click="handleApprove(record, 1)"
               href="javascript:void(0);"
               style="color: #389FFD">同意</a>
             <a-divider type="vertical" />
             <a
               @click="handleApprove(record,0)"
               href="javascript:void(0);"
               style="color: #FFAD25">否决</a>
          </template>
          <template v-else>
             <a
               @click="lookHistory(record)"
               href="javascript:void(0);"
               style="color: #FFAD25">审批历史</a>
            <a-divider type="vertical" />
             <a
               @click="lookDetail(record)"
               href="javascript:void(0);"
               style="color: #999">详情</a>
          </template>
        </span>
      </a-table>
    </div>
    <transition name="slide-fade">
      <div class="popContainer" v-if="showChild">
        <approve-form
          v-if="openType === 1"
          :show-child.sync="showChild"
          :detail-info = "detailInfo"
          :approve-type="approveType"
          @approve="handelSubmit"></approve-form>
        <historic-detail
          v-if="openType === 2"
          :show-child.sync="showChild"
          :procInstId="procInstId"></historic-detail>
        <apply-detail
          v-if="openType === 3"
          :show-child.sync="showChild"
          :detail-info = "detailInfo"
        ></apply-detail>
      </div>
    </transition>
  </div>
</template>
<script>
import { ApproveForm, ApplyDetail}  from './modules/ApproveComp'
import { TagBox } from '@/myComponents'
import HistoricDetail from '@/views/leaveManage/modules/HistoricDetail'
import {getApproveDoneList, getApproveToDoList, approveList, getAction, postFormAction } from "@/api/process";
import {objToQuery} from "@/utils/util";
export default {
  name: 'Approve',
  components: {
    ApproveForm,
    TagBox,
    HistoricDetail,
    ApplyDetail
  },
  data () {
    return {
      queryParam: {},
      showDetail: false,
      detailInfo: {},
      openType: 1,
      showChild: false,
      paginationInfo: {
        showSizeChanger: true,
        total: 0,
        current: 1,
        pageSizeOptions: ['5', '10', '15'],
        pageSize: 5,
        params: {}
      },
      tableData: [],
      listData: [],
      loading: false,
      columns: [
        {
          title: '#',
          width: 50,
          align: 'center',
          dataIndex: '',
          customRender: (t, r, index) => {
            return ((this.paginationInfo.current - 1) * this.paginationInfo.pageSize + index + 1)
          }
        },
        {
          title: '用户名',
          width: 60,
          align: 'center',
          dataIndex: 'applyer',
        },
        {
          title: '部门名称',
          width: 90,
          align: 'center',
          dataIndex: 'departName'
        },
        {
          title: '请假类型',
          width: 120,
          dataIndex: 'leaveDetailForm.leaveType',
          align: 'center',
          scopedSlots: { customRender: 'leaveTypeAction' },
        },
        {
          title: '开始时间',
          width: 60,
          dataIndex: 'leaveDetailForm.startTime',
          align: 'center'
          // sorter:true
        },
        {
          title: '结束时间',
          width: 60,
          dataIndex: 'leaveDetailForm.endTime',
          align: 'center'
        },
        {
          title: '操作', width: 120,
          dataIndex: '',
          scopedSlots: { customRender: 'action' },
          align: "center",
        }
      ],
      url: {
        donelist: '/actTask/doneList',
        todoList: '/actTask/todoList',
        pass: '/actTask/pass',
        back: '/actTask/back',
        backToTask: '/actTask/backToTask',
        delegate: '/actTask/delegate',
        getNextNode: '/activiti_process/getNextNode',
        getNode: '/activiti_process/getNode/',
        getBackList: '/actTask/getBackList/',
        passAll: '/actTask/passAll/',
        backAll: '/actTask/backAll/',
      },
      todoTotal: 0,
      doneTotal: 0,
      apiType: 'todo',
      submitLoading: false, // 添加或编辑提交状态
      procInstId: 0,
      approveType: 1 // 1同意 0 驳回
    }
  },
  computed: {
    userInfo () {
      return this.$store.getters.userInfo
    },
    departments () {
      return this.$store.getters.departments
    },
    leaveTypes () {
      return this.$store.getters.leaveTypes
    }
  },
  created() {
    this.apiType = 'todo'
    this.getToDoneAndDoneList()
  },
  mounted () {
    this.$store.dispatch('setLeaveTypes')
  },
  methods: {
    filterDictOptions (value) {
      return _.find(this.leaveTypes, function (o) {
        return o.item_val === value
      })
    },
    showDataLocal () {
      this.loading = true
      const tableData = this.tableData
      const num = this.paginationInfo.current
      const size = this.paginationInfo.pageSize
      this.listData = tableData.slice((num -1)*size, size*num)
      this.loading = false
    },
    handleTableChange (pagination, filters, sorter) {
      this.paginationInfo = pagination;
      this.showDataLocal()
    },
    toggleStatus (status) {
      this.apiType = status
      this.initList()
    },
    async initList () {
      let params = {}
      let url = ''
      if (this.apiType === 'todo') {
        params = {
          loginUserId: this.userInfo.id,
          name: ''
        }
        url = this.url.todoList
      } else if (this.apiType === 'done') {
        params = {
          _t: Date.parse(new Date()) / 1000,
          column: 'createTime',
          order: 'desc',
          loginUserId: this.userInfo.id,
          name: ''
        }
        url = this.url.donelist
      }
      this.loading = true
      const data = await approveList(url, objToQuery(params))
      this.loading = false
      if (data.success) {
        let result = []
        if (this.apiType == 'done') {
          for (let i = 0; i < data.result.length; i++) {
            if (data.result[i]['leaveStatus'] != '已撤回') {
              result.push(data.result[i])
            }
          }
        } else {
          result = data.result
        }

        this.handleTableData(result, this.queryParam)
      } else {
        this.$message.error(data.message)
        this.tableData = this.listData = []
      }
      console.log('this.tableData', this.tableData)
    },
    getToDoneAndDoneList () {
      let p1 = new Promise((resolve, reject) => {
        const params = {
          loginUserId: this.userInfo.id,
          name: ''
        }
        this.loading = true
         getApproveToDoList(objToQuery(params)).then((data) => {
           if (data.success) {
            resolve(data)
           } else {
             reject(data)
           }
         }, (error) => {
           resolve(error)
         })
      }).finally(() => {this.loading = false})

      let p2 = new Promise((resolve, reject) => {
        const params = {
          _t: Date.parse(new Date()) / 1000,
          column: 'createTime',
          order: 'desc',
          loginUserId: this.userInfo.id,
          name: ''
        }
        getApproveDoneList(objToQuery(params)).then(data => {
          if (data.success) {
            resolve(data)
          } else {
            reject(data)
          }
        }, error => {
          reject(error)
        })
      })

      Promise.all([p1, p2]).then((result) => {
        console.log('result', result)               //['成功了', 'success']
        const todoList = result[0].result
        const doneList = result[1].result
        this.todoTotal = todoList.length
        let doneRes = []
        for (let i = 0; i < doneList.length; i++) {
          if (doneList[i]['leaveStatus'] != '已撤回') {
            doneRes.push(doneList[i])
          }
        }
        this.doneTotal = doneRes.length
        if (this.apiType === 'todo') {
          this.handleTableData(todoList, {})
        } else if (this.apiType === 'done') {
          this.handleTableData(doneRes, {})
        }
      }).catch((error) => {
        console.log(error)
        this.$message.error(error.message)
      })
    },
    // 查询
    selectApprove (type) {
      // 1 查询 2 重置
      if (type === 1) {
        this.initList()
      } else if (type === 2) {
        this.queryParam = {}
        this.initList()
      }
    },
    handleTableData (tableData, queryParams = {}) {
      let list = []
      console.log('handleTableData', tableData, queryParams)
      if (queryParams.userName && queryParams.dept) {
        list = _.filter(tableData, function (o) {
          return o.applyer.indexOf(queryParams.userName) > -1 && queryParams.dept === o.departName
        }) || []
        this.paginationInfo.total = list.length
        this.paginationInfo.current = 1
        this.paginationInfo.pageSize = 5
        if (this.apiType === 'todo') {
          this.todoTotal = this.paginationInfo.total
        } else if (this.apiType === 'done') {
          this.doneTotal = this.paginationInfo.total
        }
        this.tableData = list
        this.listData = list.slice(0, this.paginationInfo.pageSize)
      }
      if (!queryParams.userName && queryParams.dept) {
        list = _.filter(tableData, function (o) {
          return queryParams.dept === o.departName
        }) || []
        console.log(list)
        this.paginationInfo.total = list.length
        this.paginationInfo.current = 1
        this.paginationInfo.pageSize = 5
        if (this.apiType === 'todo') {
          this.todoTotal = this.paginationInfo.total
        } else if (this.apiType === 'done') {
          this.doneTotal = this.paginationInfo.total
        }
        this.tableData = list
        this.listData = list.slice(0, this.paginationInfo.pageSize)
      }
      if (queryParams.userName && !queryParams.dept) {
        list = _.filter(tableData, function (o) {
          return o.applyer.indexOf(queryParams.userName) > -1
        }) || []
        console.log('applyer', list)
        this.paginationInfo.total = list.length
        this.paginationInfo.current = 1
        this.paginationInfo.pageSize = 5
        if (this.apiType === 'todo') {
          this.todoTotal = this.paginationInfo.total
        } else if (this.apiType === 'done') {
          this.doneTotal = this.paginationInfo.total
        }
        this.tableData = list
        this.listData = list.slice(0, this.paginationInfo.pageSize)
      }
      if (!queryParams.userName && !queryParams.dept) {
        this.paginationInfo.total = tableData.length
        this.paginationInfo.current = 1
        this.paginationInfo.pageSize = 5
        if (this.apiType === 'todo') {
          this.todoTotal = this.paginationInfo.total
        } else if (this.apiType === 'done') {
          this.doneTotal = this.paginationInfo.total
        }
        this.tableData = tableData
        this.listData = tableData.slice(0, this.paginationInfo.pageSize)
      }
    },
    handelSubmit(params, showAssign) {
      console.log("提交", params)
      this.submitLoading = true;
      var formData = Object.assign({},params);
      formData.loginUserId = this.userInfo.id
      if (formData.type == 0) {
        // 通过
        if (showAssign && formData.assignees == '') {
          this.$message.error("请选择一个审批人")
          this.submitLoading = false;
          return;
        } else {
          this.error = "";
        }
        postFormAction(this.url.pass, formData).then(res => {
          this.submitLoading = false;
          if (res['success']) {
            this.$message.success("操作成功");
            this.initList();
          }
        }).catch( error => {
          this.$message.error(res.message);
        });
      } else if (formData.type == 1) {
        // 驳回
        if (formData.backTaskKey == "-1") {
          // 驳回至发起人
          postFormAction(this.url.back,formData).then(res => {
            this.submitLoading = false;
            if (res.success) {
              this.$message.success("操作成功");
              this.modalTaskVisible = false;
              this.initList();
            }
          });
        } else {
          // 自定义驳回
          if (formData.backTaskKey != "-1" && formData.assignees.length < 1) {
            this.$message.error("请至少选择一个审批人")
            this.submitLoading = false;
            return;
          } else {
           // this.error = "";
          }
          postFormAction(this.url.backToTask,formData).then(res => {
            this.submitLoading = false;
            if (res['success']) {
              this.$message.success("操作成功");
             // this.modalTaskVisible = false;
              this.initList();
            }
          }).catch(error => {
            this.$message.error(res.message)
          })
        }
      } else if (formData.type == 2) {
        // 委托
        if (!formData.userId) {
          this.$message.error("请选择一委托人")
          this.submitLoading = false;
          return;
        } else {
         // this.error = "";
        }
        formData.loginUserId = this.userInfo.id
        postFormAction(this.url.delegate,formData).then(res => {
          this.submitLoading = false;
          if (res['success']) {
            this.$message.success("操作成功");
            // this.modalTaskVisible = false;
            this.initList();
          }
        });
      }
    },
    lookHistory (row) {
      this.showChild = true
      this.openType = 2
      this.procInstId = row.procInstId
    },
    handleApprove (row, type) {
      this.openType = 1
      this.detailInfo = row
      this.approveType = type
      this.showChild = true
    },
    lookDetail (row) {
      console.log('lookDetail', row)
      this.openType = 3
      this.detailInfo = row
      this.showChild = true
    }
  }
}
</script>

<style scoped>

</style>
